package com.mgfireworks.mgplatform.mgshop.main;

import cn.hn.java.summer.db.BaseDao;
import cn.hn.java.summer.db.multiple.DataSource1;
import cn.hn.java.summer.utils.JsonUtils;
import com.mgfireworks.mgplatform.mgshop.model.map.GeographyInfo;
import com.mgfireworks.mgplatform.mgshop.model.map.MapApiConfig;
import com.mgfireworks.mgplatform.mgshop.model.map.MapPoint;
import com.mgfireworks.mgplatform.mgshop.model.OrganizationVo;
import com.mzlion.easyokhttp.HttpClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * Created by xw2sy on 2017-04-03.
 */
@Service
public class AreaService extends BaseDao<DataSource1>{

    @Autowired
    private MapApiConfig mapApiConfig;

    /**
     * 检查地图上一点是否在多边形内
     * @param point 点
     * @param points 多边形
     * @return 是否
     */
    public boolean  checkMapPointIsPolygon(MapPoint point, MapPoint[] points){
        boolean c=false;
        int i=-1;
        int l=points.length;
        int j=l-1;
        for (; ++i < l; j = i) {
            if((
                (points[i].getLat() <= point.getLat() && point.getLat() < points[j].getLat()) ||
                (points[j].getLat() <= point.getLat() && point.getLat() < points[i].getLat())
            ) &&
            (point.getLng() < (points[j].getLng() - points[i].getLng()) * (point.getLat() - points[i].getLat()) / (points[j].getLat() - points[i].getLat()) + points[i].getLng())){
                c=!c;
            }
        }
        return c;
    }

    /**
     * 使用地址取地理位置信息
     * @param address 地址
     * @return 地理位置信息
     */
    public GeographyInfo getGeographyInfoByAddress(String address){
        String result=
                HttpClient.get("http://api.map.baidu.com/geocoder/v2")
                .queryString("address",address)
                .queryString("output","json")
                .queryString("ak",mapApiConfig.getAk())
                .asString();
        return JsonUtils.parse(result,GeographyInfo.class);
    }

    /**
     * 检查地址是否在2级代理商区域内
     * @param address 待检查地址
     * @param orgId 代理遇id
     * @return 是否
     */
    public boolean checkAddressIsInAgentArea(String address, int orgId){
        //取代理商信息
        OrganizationVo org= get(OrganizationVo.class,ce().set("orgId",orgId));
        String marks= org.getRangeMarks();
        //代理商运营范围标记点
        MapPoint[] points= JsonUtils.parse(marks,MapPoint[].class);
        //通过地址获取地理位置信息
        GeographyInfo geographyInfo= getGeographyInfoByAddress(address);
        //判断点是否在多边形内
        return checkMapPointIsPolygon(geographyInfo.getLocation(),points);
    }

    /**
     * 使用区域全名取代理商
     * @param areaFullName 区域全名：xx省,xx市,xx县/区
     * @return
     */
    public List<OrganizationVo> getOrgsByAreaFullName(String areaFullName){
        return list(OrganizationVo.class,ce().set("areaFullName",areaFullName));
    }
}
